﻿using System;
using System.Windows.Forms;
using System.Reflection;
using FarsiLibrary.Win;
using System.IO;
using Relocation.Data;
using Relocation.Classes;
using Relocation.Base;
using Relocation.Com;
using System.Linq;
using Relocation.Controls;
using Relocation.Base.UI;

namespace Relocation
{
	public partial class MainWindow : BaseForm
	{
		public MainWindow():base()
		{
			Initialize();
		}

		public MainWindow(Session session):base(session)
		{
			Initialize();
			this.InitUser(this.Session.User);
		}

		/// <summary>
		/// 初始化
		/// </summary>
		private void Initialize()
		{
			InitializeComponent();
			InitializeRole();			
		}

		/// <summary>
		/// 初始化权限
		/// </summary>
		private void InitializeRole()
		{
			ControlTag tag = new ControlTag(new RoleInfo(Session.KEY_ROLE_ADMIN));
			this.userManager.Tag = tag;
			this.dataImport.Tag = tag;
			this.dataExport.Tag = tag;
		}

		private void MainWindow_Load(object sender, EventArgs e)
		{
			object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
			if (attributes.Length > 0)
			{
				this.Text = ((AssemblyProductAttribute)attributes[0]).Product;
			}
			loginLoad();
		}


		public void loginLoad()
		{
			try
			{
				InitUser(this.Session.User);				
				Projects project = this.GetProject();
				if (project == null)
				{
					Application.Exit();
					return;
				}
				InitProject(project);
				//CreateMainTreeView();				

			} catch (Exception ex)
			{
				Log.Error(ex.Message);
				MyMessagebox.Error("操作失败！");
			}
		}

		private void InitProject(Projects project)
		{
			this.Session.Project = project;
			this.curProject.Text = Session.Project.projectName;

            //关闭所有选项卡
            while (this.faTabStrip.Items.Count > 0)
                this.faTabStrip.RemoveTab(this.faTabStrip.Items[0]);
            this.CreateMainTreeView(this.Session);
		}

		private void InitUser(User user)
		{
			this.curUser.Text = Session.User.name;
			this.Session.User=user;
		}

        private void CreateMainTreeView(Session session)
        {
            MainTreeView mainTreeView = new MainTreeView(session);
            mainTreeView.Dock = DockStyle.Fill;
            this.faTabStrip.AddTab(new FATabStripItem("快速搜索", mainTreeView), true);
            this.Session.DataRefresh = true;
            mainTreeView.Refresh();
            session.SetMainTreeView(mainTreeView);
        }

		/*private MainTreeView CreateMainTreeView()
		{
			MainTreeView mainTreeView = new MainTreeView(this.Session);
			mainTreeView.Dock = DockStyle.Fill;
			mainTreeView.init();
			this.Session.SetMainTreeView(mainTreeView);
			while (this.faTabStrip.Items.Count > 0)
				this.faTabStrip.RemoveTab(this.faTabStrip.Items[0]);
			this.faTabStrip.AddTab(new FATabStripItem("快速搜索", mainTreeView), true);
			mainTreeView.treeView.ExpandAll();
			return mainTreeView;
		}*/

		public void ShowForm(Form form)
		{
			foreach (FATabStripItem item in this.faTabStrip.Items)
			{
				if (item.Title == form.Text)
				{
					this.faTabStrip.SelectedItem = item;
					return;
				}
			}
			form.TopLevel = false;
			form.FormBorderStyle = FormBorderStyle.None;
			this.faTabStrip.AddTab(new FATabStripItem(form.Text, form), true);
			form.Dock = DockStyle.Fill;
			form.Show();
		}

		//项目管理
		private void projectList_Click(object sender, EventArgs e)
		{
			ShowForm(new projectList(Session));
		}
		//拆迁户管理
		private void relocateList_Click(object sender, EventArgs e)
		{
			ShowForm(new relocateList(Session));
		}
		//查询统计
		private void Statistics_Click(object sender, EventArgs e)
		{
			ShowForm(new Statistics(Session));
		}

		//项目选择
		public void projectChoose_Click(object sender, EventArgs e)
		{
			Projects project = this.GetProject();
			if (project == null)
				return;			
			this.InitProject(project);
			//this.CreateMainTreeView();
		}

		//用户管理
		private void userManager_Click(object sender, EventArgs e)
		{
			ShowForm(new UserList(Session));
		}

		#region  数据库导入导出

		//数据库导出备份
		private void dataExport_Click(object sender, EventArgs e)
		{
			string DefaultDirectory;
			if (!Application.StartupPath.EndsWith(@"\"))
				DefaultDirectory = Application.StartupPath;
			else
				DefaultDirectory = Application.StartupPath.Remove(Application.StartupPath.Length - 1, 1);

			DefaultDirectory = DefaultDirectory + @"\DataBackup\";

			if (!Directory.Exists(DefaultDirectory))
				Directory.CreateDirectory(DefaultDirectory);

			SaveFileDialog saveDialog = new SaveFileDialog();
			saveDialog.Title = "请选您要保存备份文件的位置";
			saveDialog.DefaultExt = ".bak";
			saveDialog.AddExtension = true;
			saveDialog.CheckPathExists = true;
			saveDialog.Filter = "数据库备份文件 (*.bak)|*.bak";
			saveDialog.FilterIndex = 0;
			saveDialog.InitialDirectory = DefaultDirectory;
			saveDialog.FileName = DefaultDirectory + System.DateTime.Now.ToLongDateString() + ".bak";
			DialogResult dialogResult = saveDialog.ShowDialog();
			if (!dialogResult.Equals(DialogResult.OK))
				return;

			string fileName = saveDialog.FileName;

			if (File.Exists(fileName))
				File.Delete(fileName);
			string tempPath = Application.StartupPath + @"\" + DateTime.Now.ToFileTime().ToString();

			DataBackup(tempPath);
			File.Move(tempPath, fileName);
			MyMessagebox.Show("备份成功！");
			return;
		}

		/// <summary>
		/// 数据库备份
		/// </summary>
		/// <param name="objectContext">ObjectContext对象</param>
		/// <param name="filePath">目标文件路径</param>
		private void DataBackup(string filePath)
		{
			DataModel objectContext = new DataModel();

			string directoryName = Path.GetDirectoryName(filePath);
			if (!Directory.Exists(directoryName))
				Directory.CreateDirectory(directoryName);

			if (File.Exists(filePath))
				throw new Exception("目标文件已存在");

			string DataBaseName = "Relocation";

			string SqlString = @"BACKUP DATABASE " + DataBaseName + " TO DISK = '" + filePath + "'";

			using (objectContext)
			{
				var bindingFlags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
				var factoryProperty = typeof(System.Data.EntityClient.EntityConnection).GetProperty("StoreProviderFactory", bindingFlags);
				var factory = factoryProperty.GetValue(objectContext.Connection, null) as System.Data.Common.DbProviderFactory;
				var connStr = (objectContext.Connection as System.Data.EntityClient.EntityConnection).StoreConnection.ConnectionString;

				using (var conn = factory.CreateConnection())
				{
					conn.ConnectionString = connStr;
					conn.Open();
					try
					{
						var cmd = factory.CreateCommand();
						cmd.Connection = conn;
						cmd.CommandText = SqlString;
						cmd.ExecuteNonQuery();
						cmd.Dispose();

					} catch (Exception ex)
					{
						Log.Error("数据库备份错误:" + ex.Message);
						throw;
					} finally
					{
						conn.Close();
					}
				}
			}
		}

		//数据库导入还原
		private void dataImport_Click(object sender, EventArgs e)
		{
			string DefaultDirectory;
			if (!Application.StartupPath.EndsWith(@"\"))
				DefaultDirectory = Application.StartupPath;
			else
				DefaultDirectory = Application.StartupPath.Remove(Application.StartupPath.Length - 1, 1);

			DefaultDirectory = DefaultDirectory + @"\DataBackup\";
			if (!Directory.Exists(DefaultDirectory))
				Directory.CreateDirectory(DefaultDirectory);

			OpenFileDialog open = new OpenFileDialog();
			open.Title = "请选择数据库的备份文件";
			open.AddExtension = true;
			open.CheckPathExists = true;
			open.Filter = "数据库备份文件 (*.bak)|*.bak";
			open.FilterIndex = 0;
			open.Multiselect = false;
			open.InitialDirectory = DefaultDirectory;
			DialogResult dialogResult = open.ShowDialog();
			if (!dialogResult.Equals(DialogResult.OK))
				return;

			if (!MyMessagebox.Confirm("自上次备份以来的所有数据将丢失,是否继续?").Equals(DialogResult.Yes))
				return;

			string fileName = open.FileName;
			DataRestore(fileName);
			MyMessagebox.Show("恢复成功，请重新打开本系统！");
			Application.Exit();
		}

		/// <summary>
		/// 数据库还原
		/// </summary>
		/// <param name="objectContext">ObjectContext</param>
		/// <param name="filePath">备份文件路径</param>
		private void DataRestore(string filePath)
		{
			DataModel objectContext = new DataModel();
			//判断文件是否存在
			if (!File.Exists(filePath))
				throw new Exception("备份数据库未找到!");
			//数据库名
			string DataBaseName = "Relocation";
			//构建恢复数据库的sql脚本
			string SqlString = @"use master;alter database " + DataBaseName + " set offline with rollback immediate;restore database " + DataBaseName + " from disk = '" + filePath + "'  with replace";

			using (objectContext)
			{
				var bindingFlags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
				var factoryProperty = typeof(System.Data.EntityClient.EntityConnection).GetProperty("StoreProviderFactory", bindingFlags);
				var factory = factoryProperty.GetValue(objectContext.Connection, null) as System.Data.Common.DbProviderFactory;
				var connStr = (objectContext.Connection as System.Data.EntityClient.EntityConnection).StoreConnection.ConnectionString;

				using (var conn = factory.CreateConnection())
				{
					conn.ConnectionString = connStr;
					conn.Open();
					try
					{
						var cmd = factory.CreateCommand();
						cmd.Connection = conn;
						cmd.CommandText = SqlString;
						cmd.ExecuteNonQuery();
						cmd.Dispose();

					} catch (Exception ex)
					{
						Log.Error("数据库还原错误:" + ex.Message);
						throw;
					} finally
					{
						conn.Close();
					}
				}
			}

		}

		#endregion

		//修改密码
		private void modifyPassword_Click(object sender, EventArgs e)
		{
			PwdModify pwdModify = new PwdModify(Session);
			pwdModify.ShowDialog();
		}

		//切换用户
		private void switchUser_Click(object sender, EventArgs e)
		{			
			User user = this.GetUser();
			if (user == null)
				return;
			Projects project = this.GetProject();
			if (project == null)
				return;
			this.InitUser(user);
			this.InitProject(project);
			//this.CreateMainTreeView();
		}

		//关于
		private void aboutBox_Click(object sender, EventArgs e)
		{
			using (AboutBox aboutBox = new AboutBox())
			{
				aboutBox.ShowDialog();
			}			
		}

		//退出
		private void exitWindow_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}

		private void faTabStrip_TabStripItemClosing(TabStripItemClosingEventArgs e)
		{
			if (e.Item.Title == "快速搜索")
			{
				e.Cancel = true;
				return;
			}
			if (this.faTabStrip.Items.Count > 1)
			{
				Form form = e.Item.Controls[0] as Form;
				if (form!=null)
				{
					form.Close();
				}
			} else
			{
				e.Cancel = true;
			}
		}

		private void faTabStrip_TabStripItemSelectionChanged(TabStripItemChangedEventArgs e)
		{
			if (e.Item.Controls.Count > 0)
			{
				e.Item.Controls[0].Refresh();
				e.Item.Controls[0].Focus();
			}
		}

		//快速搜索
		private void QuickSearch_Click(object sender, EventArgs e)
		{
			foreach (FATabStripItem item in this.faTabStrip.Items)
			{
				if (item.Title == "快速搜索")
				{
					this.faTabStrip.SelectedItem = item;
					return;
				}
			}
			Relocation.Controls.MainTreeView treeView = new Relocation.Controls.MainTreeView(this.Session);
			treeView.init();
			this.faTabStrip.AddTab(new FATabStripItem("快速搜索", treeView), true);
			treeView.Dock = DockStyle.Fill;
		}

		//帮助手册
		private void menuHelp_Click(object sender, EventArgs e)
		{
			//    string helpFile = @"操作手册.doc";
			//    if (System.IO.File.Exists(helpFile)) Process.Start(helpFile);
			//    else MyMessagebox.Show(@"对不起，未找到帮助文件（" + helpFile + "）！");
		}

		/// <summary>
		/// 打印
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void toolStripMenuItem3_Click(object sender, EventArgs e)
		{
			if (this.faTabStrip.SelectedItem.Controls.Count > 0)
			{
				if (this.faTabStrip.SelectedItem.Controls[0] is IPrintForm)
				{
					try
					{
						((IPrintForm)this.faTabStrip.SelectedItem.Controls[0]).Print();
					} catch (Exception ex)
					{
						Log.Error(ex);
						MyMessagebox.Error(ex.Message);
					}
				} else
				{
					MyMessagebox.Show("该页面暂无打印功能!");
				}
			}
		}

		private void toolStripMenuItem4_Click(object sender, EventArgs e)
		{
			ShowForm(new huiqian(Session));
		}

		/// <summary>
		/// 返回用户选择的项目
		/// </summary>
		/// <returns></returns>
		private Projects GetProject()
		{
			if (this.Session.DataModel.Projects.Any())
			{
				using (projectSelect pSelect = new projectSelect(Session))
				{
					pSelect.ShowDialog(this);
					return pSelect.Project;
				}
			} else
			{
				using (ProjectWindow window = new ProjectWindow(this.Session))
				{
					window.ShowDialog();
					return window.Project;
				}
			}

		}

		private User GetUser()
		{
			LoginWindow loginWindow = new LoginWindow(this.Session);
			loginWindow.ShowDialog();
			return loginWindow.User;
		}

	}
}
